// pages/comment/mycomment/mycomment.js
const showCount = 20;
let currentPage = 1;
let totalPage = 1;
import {
  getStorageItem,
  getToken,
  setStorageItem
} from '../../../utils/storage'

// import {uploadimg} from '@/api/identify'
import {
  getAllComments,
  addQrCode,
  replyUser,
  // getMyComment
} from '../../../api/comment'
import {
  showWxToast,
  showWxLoading,
  hideWxLoading,
} from "../../../utils/index";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false,
    comments: [],
    activeTab: 0,
    // uploadimg: '',
    loading: false,
    placeholderImg: 'https://ustatic.joymew.com/joymew-assist/comment/desk-comment.jpg',
    name: getStorageItem('user_name'),
    score: getStorageItem('sf_avg') || 5,
    headImg: getStorageItem('headerImgPath'),
    comment_json: getStorageItem('comment_json'),
    totalResult: 0,
    // 回复input
    showInput: false,
    album_comment_id: null,
    content: '',
    focus: true,
    splid: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {

    this.getHostCommentList();
    // this.getMyCommentInfo()

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      name: getStorageItem('user_name'),
      score: getStorageItem('sf_avg') || 5,
      headImg: getStorageItem('headerImgPath'),
      comment_json: getStorageItem('comment_json'),
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (currentPage < totalPage) {
      currentPage++
      this.getHostCommentList();
    } else {
      showWxToast("没有更多评价了");
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  changeTab(e) {
    const {
      tab
    } = e.target.dataset

    if (!this.data.comment_json && Number(tab) === 1) {
      this.uploadImg()
      this.setData({
        activeTab: Number(tab)
      })
      return;
    }
    this.setData({
      activeTab: Number(tab)
    })
  },

  getHostCommentList() {
    if (this.data.loading) {
      // showWxToast('加载中')
      this.setData({
        loading: true,
      });
      return;
    }
    showWxLoading("加载中");
    getAllComments({
        showCount: showCount,
        currentPage: currentPage,
      })
      .then((res) => {
        hideWxLoading();
        let {
          list
        } = res.data;
        list.forEach((item) => {
          item.time = item.comment_time;
        });


        totalPage = res.data.totalPage
        this.setData({
          loading: false,
          comments: this.data.comments.concat(list),
          totalResult: res.data.totalResult,
        });

      })
      .catch((err) => {

        hideWxLoading();
        this.setData({
          loading: false,
        });
      });
  },
  // getMyCommentInfo() {

  //   getMyComment({}).then(
  //       res => {

  //       }

  //     )
  //     .catch(err => {

  //     })
  // },
  uploadImg() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        ;
        const tempFilePaths = res.tempFilePaths
        const tmpToken = getToken();
        wx.uploadFile({
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            'token': tmpToken,
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          url: 'https://www.hudongmiao.com/beiJing/shangchuanTomcat',
          success: (res) => {
            let webidpic = JSON.parse(res.data);
            setStorageItem('comment_json', webidpic.data.filePath)
            this.setData({
              comment_json: webidpic.data.filePath
            })
            this.addQrCode(webidpic.data.filePath)
          }
        })
      }
    })
  },
  removeImg() {
    wx.showModal({
      title: '',
      content: '确定要移除二维码吗',
      success: (res) => {

        if (res.confirm) {
          this.setData({
            comment_json: '',
          })
          setStorageItem('comment_json', '')
          this.addQrCode('')
        } else if (res.cancel) {
          showWxToast('已取消')
        }

      }

    })
  },
  addQrCode(comment_json) {

    addQrCode(comment_json).then(res => {
        showWxToast('操作成功')
      })
      .catch(err => {
        showWxToast('操作失败')

      })
  },
  promptDelete() {
    // wx.showToast({
    //   title: '请去具体活动页处理',
    //   icon: 'none'
    // })
  },
  replyUser(e) {
    
    const {
      album_comment_id,
      name,
      splid,
    } = e.detail
    this.setData({
      album_comment_id,
      showInput: true,
      focus: true,
      activeUserName: name,
      splid,
    })
  },
  fetchReplyUser({
    splid,
    content,
    album_comment_id
  }) {
    replyUser({
        album_comment_id,
        content,
        splid,
      }).then(res => {
        wx.showToast({
          title: '发送成功',
          icon: 'none'
        })
        setTimeout(() => {
          this.setData({
            comments: [],
            content:'',
          })
          // this.comments =[];
          currentPage = 1
          totalPage = 1
          this.resetValue()
          this.getHostCommentList()
        }, 600)
      })
      .catch(err => {

      })

  },
  resetValue() {
    this.setData({
      splid: null,
      activeUserName: '',
      album_comment_id: null,
      showInput: false,

    })
  },
  inputContent(e) {

    this.setData({
      content: e.detail
    })
  },
  sendContent(e) {
    
    wx.showToast({
      title: e.detail,
    })
    if (!this.data.content) {
      wx.showToast({
        title: '请填写评论内容',
        icon: 'none'
      })
      return
    }
    this.fetchReplyUser({
      splid: this.data.splid,
      content: this.data.content,
      album_comment_id: this.data.album_comment_id,
    })


  }
})